package com.xiaochun.jiankangapp.utils

import android.annotation.SuppressLint
import android.webkit.WebSettings
import android.webkit.WebView
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.media3.common.AudioAttributes
import androidx.media3.common.MediaItem
import androidx.media3.common.PlaybackException
import androidx.media3.common.Player.Listener
import androidx.media3.database.StandaloneDatabaseProvider
import androidx.media3.datasource.DefaultHttpDataSource
import androidx.media3.datasource.cache.CacheDataSource
import androidx.media3.datasource.cache.LeastRecentlyUsedCacheEvictor
import androidx.media3.datasource.cache.SimpleCache
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.source.ProgressiveMediaSource
import com.xiaochun.jiankangapp.base.AppContext
import java.io.File

@SuppressLint("UnsafeOptInUsageError")
class VoicePlayer() : DefaultLifecycleObserver {
    companion object {
        /**
         * 媒体文件模块缓存
         */
        @JvmStatic
        private val cache = SimpleCache(
            File(AppContext.globalContext().cacheDir, "file").apply {
                if (!exists()) {
                    mkdirs()
                }
            },
            //ExoPlayer 默认提供的实现是 根据文件夹大小来自动释放旧的缓存，暂定30M，按一个视频5-8M来算，能缓存2-6个视频
            LeastRecentlyUsedCacheEvictor(200 * 1024 * 1024L),
            StandaloneDatabaseProvider(AppContext.globalContext())
        )

        @JvmStatic
        private val factory = CacheDataSource.Factory().setCache(cache)
            .setUpstreamDataSourceFactory(
                DefaultHttpDataSource.Factory()
                    .setUserAgent(WebSettings.getDefaultUserAgent(AppContext.globalContext()))
            )
    }

    val player = ExoPlayer.Builder(AppContext.globalContext()).build().apply {
        addListener(object : Listener {
            override fun onPlayerError(error: PlaybackException) {
                super.onPlayerError(error)
                error.printStackTrace()
            }

            override fun onAudioAttributesChanged(audioAttributes: AudioAttributes) {
                super.onAudioAttributesChanged(audioAttributes)
            }

            override fun onAudioSessionIdChanged(audioSessionId: Int) {
                super.onAudioSessionIdChanged(audioSessionId)
            }

            override fun onPlaybackStateChanged(playbackState: Int) {
                super.onPlaybackStateChanged(playbackState)
            }

            override fun onIsPlayingChanged(isPlaying: Boolean) {
                super.onIsPlayingChanged(isPlaying)
            }
        })
    }

    fun startPlay(url: String?) {
        if (url.isNullOrEmpty()) {
            player.stop()
            return
        }
        player.setMediaSource(
            ProgressiveMediaSource.Factory(factory)
                .createMediaSource(MediaItem.fromUri(url))
        )
        player.playWhenReady = true
        player.prepare()
    }

    fun stop() {
        player.stop()
    }

    override fun onDestroy(owner: LifecycleOwner) {
        super.onDestroy(owner)
        stop()
        player.release()
    }

}